package com.example.emos.workflow.bpmn;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import com.example.emos.workflow.config.QuartzUtil;
import com.example.emos.workflow.service.MeetingService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.JavaDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class NotifyMeetingService implements JavaDelegate {
    @Autowired
    private QuartzUtil quartzUtil;
    @Autowired
    private MeetingService meetingService;

    @Override
    public void execute(DelegateExecution delegateExecution) {
        //获取全局变量
        Map map = delegateExecution.getVariables();
        String uuid = MapUtil.getStr(map, "uuid");
        String url = MapUtil.getStr(map, "url");
        //审批结果
        String result = MapUtil.getStr(map, "result");
        HashMap data = meetingService.searchMeetingByUUID(uuid);
        String title = MapUtil.getStr(data, "title");
        String date = MapUtil.getStr(data, "date");
        String start = MapUtil.getStr(data, "start");
        String end = MapUtil.getStr(data, "end");
        //  不管审批结果什么，只要审批结束就删除定时器
        quartzUtil.deleteJob(uuid, "会议工作流组");
        if (result.equals("同意")) {
            // 同意，更新会议状态为3
            meetingService.updateMeetingStatus(new HashMap() {{
                put("uuid", uuid);
                put("status", 3);
            }});
        } else {
            meetingService.updateMeetingStatus(new HashMap() {{
                put("uuid", uuid);
                put("status", 2);
            }});
        }
        JSONObject json = new JSONObject();
        json.set("result", result);
        json.set("uuid", uuid);
        // 获取流程id
        String processId = delegateExecution.getProcessDefinitionId();
        json.set("processId", processId);
        try {
            HttpResponse execute = HttpRequest.post(url).header("Content-Type", "application/json").body(json.toString()).execute();
            log.debug(execute.body());
        } catch (Exception e) {
            log.error("发送通知失败", e);
        }
    }
}
